package com.onepiece.common.util.str;

/**
 * Binary-Coded Decimal‎，简称BCD，称BCD码或二-十进制代码
 * @author JueYue
 * 2014年1月10日--下午2:54:39
 */
public class BcdCodec {

    /**
     * @Title: bcdToInt
     * @Description: TODO(BCD转int)
     * 
     * @param bcdNum
     * @param offset
     * @param numlen
     * @return
     * @return:int
     * 
     * @version: v1.0.0
     * @author: WANJJ
     * @date: 2011-11-17
     * 
     *        Modification History: Date Author Version Description
     *        ---------------------------------------------------------*
     *        2011-11-17 wanjj v1.0.0 修改原因
     */

    public static int bcdToInt(byte[] bcdNum, int offset, int numlen) {
        return Integer.parseInt(bcdToStr(bcdNum, offset, numlen));
    }

    /**
     * @Title: bcdToString
     * @Description: TODO(BCD转字符串)
     * 
     * @param bcdNum
     * @param offset
     * @param numlen
     * @return
     * @return:String
     * 
     * @version: v1.0.0
     * @author: WANJJ
     * @date: 2011-11-17
     * 
     *        Modification History: Date Author Version Description
     *        ---------------------------------------------------------*
     *        2011-11-17 wanjj v1.0.0 修改原因
     */

    public static String bcdToStr(byte[] bcdNum, int offset, int numlen) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < numlen; i++) {
            sb.append(Integer.toHexString((bcdNum[i + offset] & 0xf0) >> 4));
            sb.append(Integer.toHexString(bcdNum[i + offset] & 0xf));
        }
        return sb.toString();
    }

    public static byte[] strToBcd(String str) {
        return strToBcd(str, str.length());
    }

    public static byte[] strToBcd(String str, int numlen) {
        if (numlen % 2 != 0)
            numlen++;

        while (str.length() < numlen) {
            str = "0" + str;
        }

        byte[] bStr = new byte[str.length() / 2];
        char[] cs = str.toCharArray();
        int i = 0, iNum = 0, le = cs.length;
        for (; i < le; i += 2) {

            int iTemp = 0;
            if (cs[i] >= '0' && cs[i] <= '9') {
                iTemp = (cs[i] - '0') << 4;
            } else {
                // 判断是否为a~f
                if (cs[i] >= 'a' && cs[i] <= 'f') {
                    cs[i] -= 32;
                }
                iTemp = (cs[i] - '0' - 7) << 4;
            }
            // 处理低位
            if (cs[i + 1] >= '0' && cs[i + 1] <= '9') {
                iTemp += cs[i + 1] - '0';
            } else {
                // 判断是否为a~f
                if (cs[i + 1] >= 'a' && cs[i + 1] <= 'f') {
                    cs[i + 1] -= 32;
                }
                iTemp += cs[i + 1] - '0' - 7;
            }
            bStr[iNum] = (byte) iTemp;
            iNum++;
        }
        return bStr;

    }
}
